﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Windows.Threading;
using System.Linq;
using System.Xml.Linq;
using Microsoft.SharePoint.Client;

namespace Microsoft.ProductivityHub.SilverlightProductCarousel
{

    // --------------------------------------------------------------------------------
    // Data LOADER CLASS
    // --------------------------------------------------------------------------------
    
    // This class contains functions to load data from the specified document library


    public class DataLoader : UserControl
    {
        private ListItemCollection listItems = null;
        private const string _listName = "Products";
        System.Collections.Generic.List<ProductItem> products = null;
        private string currentWebUrl = null;

        private const string _allItemsCamlQuery = @"<View>
                <Query>
                  <OrderBy><FieldRef Name='Title' Ascending='TRUE'/></OrderBy>
                </Query>
                <RowLimit>900</RowLimit>
              </View>";


        public string CurrentWebUrl
        {
            get 
            { 
                return currentWebUrl; 
            }
            set 
            {
                Uri uri = new Uri(value);
                currentWebUrl = uri.AbsoluteUri;
            }
        }

        public DataLoader()
        {
        }

        public void LoadData(string webFullUrl)
        {
            if (String.IsNullOrEmpty(webFullUrl))
            {
                throw new ArgumentNullException("webFullUrl");
            }

            this.CurrentWebUrl = webFullUrl;

            ClientRequestSucceededEventHandler onSuccess = new ClientRequestSucceededEventHandler(OnSucceeded);
            ClientRequestFailedEventHandler onFailure = new ClientRequestFailedEventHandler(OnFailed);

            Microsoft.SharePoint.Client.ClientContext cc = new Microsoft.SharePoint.Client.ClientContext(this.CurrentWebUrl);

            List list = cc.Web.Lists.GetByTitle(_listName);

            CamlQuery camlQuery = new CamlQuery();

           // use the standard / default caml query
            camlQuery.ViewXml = _allItemsCamlQuery;
           

            listItems = list.GetItems(camlQuery);

            cc.Load(listItems,
                 items => items
                     .Include(
                         item => item["ID"], 
                         item => item["Title"],
                         item => item["FullTitle"],
                         item => item["IconUrl"],
                         item => item["Modified"]));

            cc.ExecuteQueryAsync(onSuccess, onFailure);

        }

        private void OnFailed(object sender, Microsoft.SharePoint.Client.ClientRequestFailedEventArgs e)
        {
            throw new Exception(e.Message + " " + e.ErrorDetails);
            //_Loaded.Invoke(null);
        }

        private string GetAbsoluteUrlForThumbnailFile(string thumbFileName)
        {
            if (String.IsNullOrEmpty(thumbFileName) || thumbFileName.Length < 3)
            {
                thumbFileName = "_layouts/images/docset_welcomepage_big.png";
            }

            string tempUrl = currentWebUrl.TrimEnd('/');
            return string.Format("{0}/SiteAssets/{1}", tempUrl, thumbFileName);
        }

        private void OnSucceeded(object sender, Microsoft.SharePoint.Client.ClientRequestSucceededEventArgs e)
        {
            // Data operations occur here
            if (listItems != null && listItems.Count > 0)
            {
                products = new System.Collections.Generic.List<ProductItem>(listItems.Count);

                // Create a VideoItem object for each list item in the list
                foreach (ListItem listItem in listItems)
                {
                    ProductItem product = new ProductItem();
                    product.ID = listItem["ID"].ToString();
                    product.ThumbnailUri = GetAbsoluteUrlForThumbnailFile((string)listItem["IconUrl"]);
                    product.Title = (string)listItem["Title"];
                    product.FullTitle = (string)listItem["FullTitle"];
                    products.Add(product);
                    
                }

                // _Loaded.Invoke(videos); // this performs the invoke on the non-UI thread
                this.Dispatcher.BeginInvoke(_Loaded, products); // this performs the invoke on the UI thread
                //Dispatcher.BeginInvoke(() => { MessageBox.Show(webHub.CurrentUser.LoginName); });
            }
            else
            {
                this.Dispatcher.BeginInvoke(_Loaded, new System.Collections.Generic.List<ProductItem>()); // this performs the invoke on the UI thread
            }

        }


        // --------------------------------------------------------------------------------
        // Data Loaded Event
        // --------------------------------------------------------------------------------

        public delegate void _DataLoaded(System.Collections.Generic.List<ProductItem> videos);
        public event _DataLoaded _Loaded;

        // --------------------- ----------------------------------------------------------

    // end class
    }
}
